<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <p>666666666666666666666</p>
</body>
<script type="text/javascript">
  function ajax(options) {
    var defaults = {
      type: 'get',
      url: '',
      data: {},
      header: {
        'ContentType': 'application/x-www-from-urlencoded'
      },
      success: function () { },
      err: function () { }

    }
    Object.assign(defaults, options)
    var xhr = new XMLHttpRequest()
    //定义一个拼接字符串
    var params = ''
    //将参数转换成字符串格式，及遍历对象
    for (var attar in defaults.data) {
      params += attar + '=' + defaults.data[attar] + '&'
    }
    //选取第一个到倒数第二个，及去掉最后一个&
    params = params.substr(0, params.length - 1)
    //判断请求方式
    if (defaults.type == 'get') {
      defaults.url = defaults.url + '?' + params
    }
    xhr.open(defaults.type, defaults.url)
    if (defaults.type == 'post') {
      //客户希望传递的类型
      var contentType = defaults.header['Content-Type']
      //设置请求参数的类型
      xhr.setRequestHeader('Content-Type', contentType)
      if (contentType == 'application/json') {
        //将对象类型转换成字符串类型
        xhr.send(JSON.stringify(defaults.data))
      }
      else {
        xhr.send(params)
      }
    }
    else {
      xhr.send()
    }
    xhr.onload = function () {
      var contentType = xhr.getResponseHeader('Content-Type')
      var responseText = xhr.responseText
      // if (contentType.includes('application/json')) {
      // responseText = JSON.parse(responseText)
      // }
      if (xhr.status == 200) {
        defaults.success(responseText, xhr)
      }
      else {
        defaults.error(responseText, xhr)
      }
    }
  }
  ajax({
    type: 'post',
    data: {
      name: 'zhan_san',
      sex: 'nan'
    },
    header: {
      'Content-Type': 'application/json'
    },
    url: 'http://localhost:3000/ui',
    success: function (data, xhr) {
      console.log(data)
    },
    error: function (data, xhr) {
      console.log(data)
    }
  })
</script>

</html>